
package org.dragonnova.iot.business.cloud.transport.model;
/**
 * * 请求包帧头格式： 
 * ****************************** * 
 * ** phone 8 byte  (电话号码) 
 */

import org.dragonnova.iot.business.cloud.transport.ParseException;
import org.dragonnova.iot.business.cloud.transport.TooShortPackageException;
import org.dragonnova.iot.business.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

/**
 * @description: 注销链接
 * @company winter
 */
public class LogoffPacket extends NPacket {
	public static final byte LOGOFF_TYPE_CODE_UNSUPPORTED_OPERATION = (byte) 0x02;
	// 注销校验码
	public static final byte LOGOFF_TYPE_CODE_CHECK = (byte) 0x12;

	private final static Logger LOGGER = LoggerFactory.getLogger(AckPacket.class);

	private long phone;

	public long getPhone() {
		return phone;
	}

	public void setPhone(long phone) {
		this.phone = phone;
	}

	public LogoffPacket() {
		this(LOGOFF_TYPE_CODE_UNSUPPORTED_OPERATION, LOGOFF_TYPE_CODE_CHECK);
	}

	public LogoffPacket(byte code, byte checkCode) {
		this.mt = code;
		this.checkCode = checkCode;
	}

	public byte getMtCode() {
		return this.mt;
	}

	@Override
	protected void decodeBody(ByteBuf byteBuf) {
		try {
			phone = byteBuf.readLong();
			this.checkCode = byteBuf.readByte();
			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("LogoffPacket Code: [\'" + this.mt + "\'] Packet.");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected ByteBuf encodeBody() {
		try {
			this.bodyLength=(short) (Long.BYTES);
			final ByteBuf buffer = Unpooled.directBuffer(this.PACK_PUBLIC_LEN+this.bodyLength);
			buffer.writeByte(Packet.HEADER);
			buffer.writeByte(this.mt);
			buffer.writeBytes(Utils.int2HLbyte((short)(this.bodyLength+this.PACK_PUBLIC_LEN)));
			buffer.writeBytes(Utils.long2HLByte(phone, Long.BYTES));
			buffer.writeByte(this.checkCode);// 校验
			buffer.writeBytes(Packet.END);
			return buffer;
		} catch (Exception e) {
			throw new ParseException("LogoffPacket encode error: caused by " + e.getMessage());
		}
	}

	@Override
	protected void releasePacket() {
	}
}
